import 'package:excel_utils/extend/string_extend.dart';
import 'package:excel_utils/pages/daily/daily_report/bean/CustomerBean.dart';
import 'package:excel_utils/pages/week/week_report/widgets/month_plan_widget.dart';
import 'package:excel_utils/repository/k8/k8_repository.dart';
import 'package:excel_utils/widgets/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'bloc/week_data_entry_cubit.dart';

class WeekDataEntryPage extends StatefulWidget {
  const WeekDataEntryPage({super.key});

  @override
  State<WeekDataEntryPage> createState() => _WeekDataEntryPageState();
}

class _WeekDataEntryPageState extends State<WeekDataEntryPage> {
  WeekDataEntryCubit? _weekDataEntryCubit;

  Map<String, dynamic> selectPlans = {};

  List<Map<String, dynamic>> _plans = [
    {"type": "M1", "keda_count": 10, "month_price": 180, "excess_charge": 19, "excess_form": "On Call"},
    {"type": "M2", "keda_count": 20, "month_price": 340, "excess_charge": 18, "excess_form": "On Call"},
    {"type": "M3", "keda_count": 30, "month_price": 470, "excess_charge": 17, "excess_form": "A.M."},
    {"type": "M5", "keda_count": 50, "month_price": 730, "excess_charge": 16, "excess_form": "A.M.+P.M."},
    {"type": "M7", "keda_count": 70, "month_price": 950, "excess_charge": 15, "excess_form": "A.M.+P.M."},
    {"type": "M10", "keda_count": 100, "month_price": 1260, "excess_charge": 14, "excess_form": "A.M.+P.M."},
    {"type": "M15", "keda_count": 150, "month_price": 1730, "excess_charge": 13, "excess_form": "A.M.+P.M."},
  ];

  // 非核心工业区
  List<Map<String, dynamic>> _plansNotZone = [
    {"type": "M1", "keda_count": 10, "month_price": 280, "excess_charge": 29, "excess_form": "On Call"},
    {"type": "M2", "keda_count": 20, "month_price": 540, "excess_charge": 28, "excess_form": "On Call"},
    {"type": "M3", "keda_count": 30, "month_price": 690, "excess_charge": 24, "excess_form": "A.M."},
    {"type": "M5", "keda_count": 50, "month_price": 1170, "excess_charge": 23, "excess_form": "A.M.+P.M."},
    {"type": "M7", "keda_count": 70, "month_price": 1390, "excess_charge": 20, "excess_form": "A.M.+P.M."},
    {"type": "M10", "keda_count": 100, "month_price": 1780, "excess_charge": 18, "excess_form": "A.M.+P.M."},
    {"type": "M15", "keda_count": 150, "month_price": 2250, "excess_charge": 16, "excess_form": "A.M.+P.M."},
  ];

  bool isCustomerSearchLoading = false;
  List<CustomerBean> customerList = [];
  TextEditingController searchCustomerNoController = TextEditingController();

  int year = 0000;
  int month = 00;
  int day = 00;
  int hour = 00;
  int minute = 00;
  int second = 00;

  @override
  void initState() {
    DateTime now = DateTime.now();
    if (now.day == 1) {
      now = now.subtract(Duration(days: 1));
    }
    year = now.year;
    month = now.month;
    day = now.day;
    hour = now.hour;
    minute = now.minute;
    second = now.second;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<WeekDataEntryCubit>(
      create: (BuildContext context) => WeekDataEntryCubit(context.read<K8Repository>()),
      child: BlocBuilder<WeekDataEntryCubit, WeekDataEntryState>(
        builder: (BuildContext context, WeekDataEntryState state) {
          _weekDataEntryCubit = _weekDataEntryCubit ?? context.read<WeekDataEntryCubit>();

          if (state is WeekDataEntryInitial) {
          } else if (state is WeekDataEntryCustomerSearchLoadingState) {
            isCustomerSearchLoading = true;
          } else if (state is WeekDataEntryCustomerSearchSuccessState) {
            isCustomerSearchLoading = false;
            customerList = state.customerData;
          } else if (state is WeekDataEntryRefreshingState) {}

          return _buildUI();
        },
      ),
    );
  }

  Widget _buildUI() {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [

          SizedBox(child: _buildCustomData()),
          Divider(height: 2, color: Colors.grey),
          // RINCOSWidget(),
          // _buildMonthlyPackage(),
        ],
      ),
    );
  }


  Widget _buildCustomData() {
    return Container(
      child: Column(
        children: [
          Text("月费调整"),
          SizedBox(height: 350, child: MonthPlanWidget()),
          (isCustomerSearchLoading)
              ? Center(child: CircularProgressIndicator())
              : ElevatedButton(
                  onPressed: () {
                    if(searchCustomerNoController.text.isEmpty) return;
                    var customerNo = searchCustomerNoController.text.trim().split('\r').map((e) => e.trim()).toList();
                    _weekDataEntryCubit?.search(customerNo: customerNo);
                  },
                  child: Text("查询")),
          SizedBox(height: 10),
          SizedBox(
            height: 100,
            child: TextField(
                controller: searchCustomerNoController,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                )),
          ),
          TextButton(
              onPressed: () {
                StringBuffer sb = StringBuffer();
                for (CustomerBean customer in customerList) {
                  for (Data data in customer.data ?? []) {
                    sb.write(
                        "${data.groupName ?? ""}\t ${data.cmCode}\t ${data.cmName}\t ${data.cmAddress}\t ${data.cmMonthcost}\t ${data.cmOrdernum}\t ${data.cmOverfull}\t"
                        " ${data.newCmMonthcost}\t ${data.newCmOrdernum}\t ${data.newCmOverfull}\n");
                  }
                }
                sb.toString().copyValue();
              },
              child: Text("Copy All")),
          Table(
            children: [
              //更改月份	所屬群組	客戶號碼	客戶名稱	地址	原月費	原柯打數	原超件費	新月費	新柯打數	新超件費	月費相差
              tabRows(["更改月份", "所屬群組", "客戶號碼", "客戶名稱", "地址", "原月費", "原柯打數", "原超件費", "选择新月费", "新月費", "新柯打數", "新超件費", "操作"]),
              ...customerList.where((element) {
                return element.data!.isNotEmpty;
              }).map((element) {
                Data? data = element.data?.single;
                if (data == null) {}
                return tabRowWidgets([
                  Text(""),
                  Text(data?.groupName ?? "", maxLines: 1),
                  Text(data?.cmCode ?? "", maxLines: 1),
                  Text(data?.cmName ?? "", maxLines: 1),
                  Text(data?.cmAddress ?? "", maxLines: 1),
                  Text(data?.cmMonthcost.toString() ?? ""),
                  Text(data?.cmOrdernum.toString() ?? ""),
                  Text(data?.cmOverfull.toString() ?? ""),
                  MenuAnchor(
                    menuChildren: [
                      Row(
                        children: [
                          Column(
                            children: [
                              Text("核心工业区"),
                              ..._plans.map((e) {
                                return TextButton(
                                    onPressed: () {
                                      selectPlans = e;
                                      element.data?.single.newCaseCode = selectPlans["type"];
                                      element.data?.single.newCmMonthcost = selectPlans["month_price"];
                                      element.data?.single.newCmOrdernum = selectPlans["keda_count"];
                                      element.data?.single.newCmOverfull = selectPlans["excess_charge"];
                                      _weekDataEntryCubit?.refresh();
                                    },
                                    child: Text(e["type"]));
                              })
                            ],
                          ),
                          SizedBox(width: 10),
                          Column(
                            children: [
                              Text("非核心工业区"),
                              ..._plansNotZone.map((e) {
                                return TextButton(
                                    onPressed: () {
                                      selectPlans = e;
                                      element.data?.single.newCaseCode = selectPlans["type"];
                                      element.data?.single.newCmMonthcost = selectPlans["month_price"];
                                      element.data?.single.newCmOrdernum = selectPlans["keda_count"];
                                      element.data?.single.newCmOverfull = selectPlans["excess_charge"];
                                      _weekDataEntryCubit?.refresh();
                                    },
                                    child: Text(e["type"]));
                              })
                            ],
                          ),
                        ],
                      ),
                    ],
                    builder: (context, controller, child) {
                      return Container(
                        child: TextButton(
                            onPressed: () {
                              if (controller.isOpen) {
                                controller.close();
                              } else {
                                controller.open();
                              }
                            },
                            child: Text(data?.newCaseCode ?? "选择月费方案")),
                      );
                    },
                  ),
                  Text("${data?.newCmMonthcost ?? 0}"),
                  Text("${data?.newCmOrdernum ?? 0}"),
                  Text("${data?.newCmOverfull ?? 0}"),
                  TextButton(
                    onPressed: () {
                      "${data?.groupName ?? ""}\t ${data?.cmCode}\t ${data?.cmName}\t ${data?.cmAddress}\t ${data?.cmMonthcost}\t ${data?.cmOrdernum}\t ${data?.cmOverfull}\t"
                              " ${data?.newCmMonthcost}\t ${data?.newCmOrdernum}\t ${data?.newCmOverfull}\t"
                          .copyValue();
                    },
                    child: Text("Copy"),
                  ),
                ]);
              })
            ],
          ),
        ],
      ),
    );
  }

  kfWidget() {
    return Container();
  }

  Widget _buildMonthlyPackage() {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10),
      decoration: BoxDecoration(
        border: Border(top: BorderSide(color: Colors.grey, width: 0.5)),
      ),
      child: Column(
        children: [
          // 请选择记录的时间
          _buildDate(onDateChanged: (onChangeDate) {}),
        ],
      ),
    );
  }

  Widget _buildDate({DateTime? currentStartDate, required Function(String) onDateChanged}) {
    return SizedBox(
      width: 200,
      height: 200,
      child: CalendarDatePicker(
          initialDate: null,
          currentDate: currentStartDate ?? DateTime(year, month, day - 1, 00, 00, 00),
          firstDate: DateTime(2020 - 10, 1, 1, 0, 0, 0),
          lastDate: DateTime(year, month, day - 1, 23, 59, 59),
          onDateChanged: (date) {
            var startTime = "${date.year}-${date.month < 9 ? "0${date.month}" : date.month}-${date.day < 9 ? "0${date.day}" : date.day} 00:00:00";
            onDateChanged(startTime);
          }),
    );
  }

  Widget _customTextField({String? label, String? hint, required TextEditingController controller, required Function(String) onChanged}) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 5),
      child: TextFormField(
        controller: controller,
        decoration: InputDecoration(
          labelText: label,
          hintText: hint,
          border: OutlineInputBorder(),
        ),
        onChanged: onChanged,
      ),
    );
  }
}
